#pragma once
#include <iostream>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Log.hpp"

#define NUM_LISTEN 5

static pthread_mutex_t _mtx = PTHREAD_MUTEX_INITIALIZER;

class TcpServer
{
private:
    int port;
    int listen_socket;
    static TcpServer *sev;

private:
    TcpServer(int _port)
        : port(_port), listen_socket(-1)
    {
    }
    TcpServer(TcpServer &tcpserver)
    {
    }

public:
    static TcpServer *GetInstance(int port)
    {
        if (sev == nullptr)
        {
            pthread_mutex_lock(&_mtx);
            if (sev == nullptr)
            {
                sev = new TcpServer(port);
                sev->InitServer();
            }
            pthread_mutex_unlock(&_mtx);
        }
        return sev;
    }

    void InitServer()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFO, "tcp_server init ... success");
    }

    void Socket()
    {
        listen_socket = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_socket < 0)
        {
            LOG(FATAL, "socket error!");
            exit(1);
        }
        int opt = 1;

        // socket地址复用，允许创建端口号相同但IP地址不同的多个socket描述符
        setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        LOG(INFO, "create socket ... success");
    }

    void Bind()
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(listen_socket, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error!");
            exit(2);
        }
        LOG(INFO, "bind socket ... success");
    }

    void Listen()
    {
        if (listen(listen_socket, NUM_LISTEN) < 0)
        {
            LOG(FATAL, "listen socket error!");
            exit(3);
        }
        LOG(INFO, "listen socket ... success");
    }

    int Sock()
    {
        return listen_socket;
    }

    ~TcpServer()
    {
        if(listen_socket >= 0)
        {
            close(listen_socket);
        }
    }
};

TcpServer *TcpServer::sev = nullptr;